package simulator;

public class AsyncBufferCache extends BufferCache {

	public AsyncBufferCache(int numFrames)
	{
		super(numFrames);
	}
		
	public void updateBlock(String fileName, int data)
	{
		//lazyCommit();
		int frameNo = findBlock(fileName);
		
		if(frameNo >= 0){
			hits++;
		}
		
		else{
		//Cache miss. For now, let's bring it into the buffer cache
			misses++;
			frameNo = readIn(fileName); //read in the data from the specified file ot the frame.
		//this is the index of our new frame of data
		}
		
		Frame f = frames[frameNo];
		f.setIsDirty(true);
		f.setData(data);
		f.timeStamp = ss.getTime();
	}
	
	
	
	// Lazy commit form BufferCache to JournalArea
	public void lazyCommit()
	{
		if(frames.length >= 50/*BufferCache is almost full, time for commit, 50 is changable*/)
		{
			commitAll();
		}
	}
	
	// Async periodically commit, called in EntryPoint.
	public void commitAll()
	{
		for(int i=0; i<frames.length; i++)
		{
			if(frames[i].isDirty == true)
			{
				ja.commitData(frames[i].getBlock());
				frames[i].isDirty = false;
			}
		}
	}

	
	public void evictDirty(Block b)
	{
		 //write back to file system if dirty
		ja.commitData(b);
		
	}

	@Override
	public void flushDirty() {
		// TODO Auto-generated method stub
		commitAll();
		ja.checkpointAll();
	}

	@Override
	public void checkpointAll() {
		// TODO Auto-generated method stub
		return;
	}

	@Override
	public String SimString() {
		// TODO Auto-generated method stub
		String str = "Sim type: Async Journaling\nHits: " + hits + "\nMisses: " + misses;
		return str;
	}
}
